<template>
  <div class="h100p toppage pb50" :class="pageFixed ? 'fix' : '' " id="CONT">
    <!--顶部-->
    <div class="pl35 pt10 textc pr35 pb9 bgfff disflex jsbet fix_top borderbox fs12 c78">
      <div @click="addWx">
        <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/im_msg.png" alt="" class="w30 h30">
        <p class="pt8">加微信</p>
      </div>
      <div @click="makePhone">
        <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/tel_blue.png" alt="" class="w30 h30">
        <p class="pt8">打电话</p>
      </div>

      <label v-if="!myPhone">
        <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/im_link.png" alt="" class="w30 h30">
        <p class="pt8">请联系我</p>
        <button open-type="getPhoneNumber"
                class="hide"
                @getphonenumber="getPhoneNumber"
        ></button>
      </label>
      <div @click="contactMe" v-else>
        <img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/im_link.png" alt="" class="w30 h30">
        <p class="pt8">请联系我</p>
      </div>
    </div>
    <!--IM内容-->
    <div class="pt123 chat-box">
      <div class="im_by_time" v-if="msgCont" v-for="(msgitem,k) in msgCont.data" :key="k">
        <!--时间-->
        <p class="lh39 fs12 ca8 textc">{{indexs[k]}}</p>
        <div class="textc" v-if="msgitem.messageType == 4">
          <div class="sys-message">
            {{seedName}} {{msgitem.sendId== myid ? '已收到你的联系方式' : '已向你发送了联系方式，尽快与他联系'}}
          </div>
        </div>
        <template v-else>
          <!--right-->
          <div class="im_right disflex pl22 pr15 im_item flex-end" v-if="msgitem.sendId== myid">
            <!--消息状态-->
            <div class="disflex column-reverse w33 fs12 ca8" v-if="msgitem.type==0">未读</div>
            <div class="disflex column-reverse w33 fs12 ca8" v-if="msgitem.type==1">已读</div>

            <!--信息-->
            <div class="im_right_msg im_msg pl15 pt10 pr18 pb10 bgblue bradius5 w250 be8 posre  "
                 v-if="msgitem.messageType==1">
              <p class="fs14 cfff im_text">{{msgitem.message}}</p>
              <span class="triangle_border_right1"></span>
            </div>
            <div class="im_left_msg im_msg pl8 pr23 pb15 pt14 bgfff bradius5 w250 be8 posre disflex"
                 v-if="msgitem.messageType==3">
              <img :src="msgitem.message.url" alt=""
                   mode="aspectFill"
                   class="w40 h40 bradius5 mr13">
              <div class="flex1">
                <p class="fs14 c38">{{msgitem.message.goodsName}}</p>
                <p class="pt5">
                  <span class="corange fs16">￥{{priceObj[k]}}</span>
                  <!--                <span class="fs12 ca8 line-through pl10">￥666</span>-->
                </p>
              </div>
              <span class="triangle_border_right"></span>
            </div>
            <div class="im_right_msg  pl15 pt14 pr18 bgfff bradius5 w250 be8 posre" v-if="msgitem.messageType==2">
              <p class="fs14 c38">你好，我是{{msgitem.message.companyName}}的{{msgitem.message.name}}，欢迎进入我的名片，有什么可以帮到你的吗？</p>
              <p class="fs12 ca8 pt10 pb9">您还可以点击查看</p>
              <div class="disflex jsbet fs12 c38 lh30 textc wrap">
                <span class="be8 bgf5f6 borderbox w104 mb10 ">企业产品</span>
                <span class="be8 bgf5f6 borderbox w104 mb10">我的名片</span>
                <span class="be8 bgf5f6 borderbox w104 mb10 ">企业官网</span>
                <span class="be8 bgf5f6 borderbox w104 mb10">企业动态</span>
              </div>
              <span class="triangle_border_right"></span>
            </div>

            <!--头像-->
            <img :src="logo" alt="" mode="aspectFill" class="im_right_img ml16 w40 h40 bradius5">
          </div>

          <!--left-->
          <div class="im_left disflex pl15 pr22 im_item" v-if="msgitem.sendId==sendId">

            <!--头像-->
            <img :src="userlogo || 'https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/crm/card1_user.png'" mode="aspectFill" alt="" class="im_left_img mr10 w40 h40 bradius5">

            <!--信息-->
            <div class="im_right_msg im_msg pl15 pt10 pr18 pb10 bgfff bradius5 w250 be8 posre word-break-all" v-if="msgitem.messageType==1">
              <p class="fs14 c38 im_text">{{msgitem.message}}</p>
              <span class="triangle_border_left"></span>
            </div>
            <div class="im_left_msg im_msg pl8 pr23 pb15 pt14 bgfff bradius5 w250 be8 posre disflex" v-if="msgitem.messageType==3">
              <img :src="msgitem.message.url" alt=""
                   mode="aspectFill"
                   class="w40 h40 bradius5 mr13">
              <div class="flex1">
                <p class="fs14 c38">{{msgitem.message.goodsName}}</p>
                <p class="pt5">
                  <span class="corange fs16">￥{{priceObj[k]}}</span>
                  <!--                <span class="fs12 ca8 line-through pl10">￥666</span>-->
                </p>
              </div>
              <span class="triangle_border_left"></span>
            </div>

            <div class="im_right_msg  pl15 pt14 pr18 bgfff bradius5 w250 be8 posre" v-if="msgitem.messageType==2">
              <p class="fs14 c38">你好，我是{{msgitem.message.companyName}}的{{msgitem.message.name}}，欢迎进入我的名片，有什么可以帮到你的吗？</p>
              <p class="fs12 ca8 pt10 pb9">您还可以点击查看</p>
              <div class="disflex jsbet fs12 c38 lh30 textc wrap">
                <span class="be8 bgf5f6 borderbox w104 mb10 ">企业产品</span>
                <span class="be8 bgf5f6 borderbox w104 mb10">我的名片</span>
                <span class="be8 bgf5f6 borderbox w104 mb10 ">企业官网</span>
                <span class="be8 bgf5f6 borderbox w104 mb10">企业动态</span>
              </div>

              <span class="triangle_border_left"></span>
            </div>

            <!--信息状态-->
            <div class="disflex textr column-reverse w33 fs12 ca8" v-if="msgitem.type==0">未读</div>
            <div class="disflex textr column-reverse w33 fs12 ca8" v-if="msgitem.type==1">已读</div>

          </div>
        </template>

      </div>
    </div>


    <!--<div class="im_by_time">-->
    <!--&lt;!&ndash;时间&ndash;&gt;-->
    <!--<p class="lh39 fs12 ca8 textc">02-23 08:05</p>-->

    <!--&lt;!&ndash;right&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="im_right disflex pl22 pr15 im_item noread">&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;信息状态&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="disflex column-reverse w33 fs12 cblue">未读</div>&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;信息&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="im_right_msg im_msg pl15 pt10 pr18 pb10 bgfff bradius5 w250 be8 posre">&ndash;&gt;-->
    <!--&lt;!&ndash;<p class="fs14 c38 im_text">壹立科技出品定为精品跑腿配送小程序出租源码出售</p>&ndash;&gt;-->
    <!--&lt;!&ndash;<span class="triangle_border_right"></span>&ndash;&gt;-->
    <!--&lt;!&ndash;</div>&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;头像&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/user.jpg" alt="" class="im_right_img ml16 w40 h40 bradius5">&ndash;&gt;-->

    <!--&lt;!&ndash;</div>&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;left&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="im_left disflex pl15 pr22 im_item">&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;头像&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<img src="https://one-stand.oss-cn-shanghai.aliyuncs.com/yimai_photos/user/user.jpg" alt="" class="im_left_img mr10 w40 h40 bradius5">&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;信息&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="im_left_msg im_msg pl8 pr23 pb15 pt14 bgfff bradius5 w250 be8 posre disflex">&ndash;&gt;-->

    <!--&lt;!&ndash;<img src="../../../static/images/food.jpg" alt="" class="w40 h40 bradius5 mr13">&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="flex1">&ndash;&gt;-->
    <!--&lt;!&ndash;<p class="fs14 c38">壹立科技出品定为精品跑腿配送小程序出租源码出售</p>&ndash;&gt;-->
    <!--&lt;!&ndash;<p class="pt5">&ndash;&gt;-->
    <!--&lt;!&ndash;<span class="corange fs16">￥99</span>&ndash;&gt;-->
    <!--&lt;!&ndash;<span class="fs12 ca8 line-through pl10">￥666</span>&ndash;&gt;-->
    <!--&lt;!&ndash;</p>&ndash;&gt;-->
    <!--&lt;!&ndash;</div>&ndash;&gt;-->

    <!--&lt;!&ndash;<span class="triangle_border_left"></span>&ndash;&gt;-->
    <!--&lt;!&ndash;</div>&ndash;&gt;-->

    <!--&lt;!&ndash;&lt;!&ndash;信息状态&ndash;&gt;&ndash;&gt;-->
    <!--&lt;!&ndash;<div class="disflex textr column-reverse w33 fs12 ca8">已读</div>&ndash;&gt;-->

    <!--&lt;!&ndash;</div>&ndash;&gt;-->


    <!--</div>-->


    <!--bottom-->
    <!--  <div class="fix_bottom im_bottom disflex pl15 pr15 pt5 pb5 bgfff jsbet borderbox">

          <div class="pt5">
              <span class="disblock lh30 w65 textc bblue cblue fs16 bradius5">常用语</span>
          </div>
          <input type="text" class="w170 bgf5f6 bradius5 pl6 lh39 h39 fs14" v-model="input_word"
                 @confirm="inputConfirm">

          <img src="./../../../static/images/usercenter/smile.png" alt="" class="w30 h30 mt5">

          <div class="pt5">
              <span class="bgblue cfff w50 textc lh30 fs16 bradius5 disblock">发送</span>
          </div>
      </div>-->
    <div class="pb50"></div>
    <EditInputer v-on:comment="getcomment"></EditInputer>

    <!--微信复制成功-->
    <div class="fix_top w100p h100p bggray_5 disflex align-cen jscen" v-show="pageFixed">
      <!--<img src="./../../../static/images/add_wx.png" alt="" class="w326 h533">-->
    </div>

    <div v-if="isShowCourse">
      <addWxCourse :isShow="isShowCourse"
                   @close="isShowCourse=false"
      />
    </div>
  </div>
</template>

<script>
  import EditInputer from '@/components/editInputer'
  import WXAJAX from '../../utils/request'
  import WebSocket from '../../utils/websocket'
  import AddWxCourse from '@/components/addWxCourse'
  import store from '../../store/index';
  import {mapGetters, mapActions} from 'vuex';
  //  import {mapState,mapActions} from 'vuex'
  export default {
    name: '',
    components: {EditInputer, AddWxCourse},
    data() {
      return {
        input_word: '',
        pageFixed: '',
        socket: null,
        messageCont: {},
        logo: '',
        myid: '',
        userlogo: '',
        sendId: '',
        times: [],
        indexs:{},
        params: {},
        priceObj: {},
        wxCode: '',
        phone: '',
        seedName: '',
        isShowCourse: false,
        appHeight: 0,
        chatHeight: 0,
        myPhone: '',
        isShow: false,
      }
    },
    filter:{
      showType(a){
        return typeof  a;
      }
    },
    mounted() {
      this.logo = wx.getStorageSync('avatarUrl') || '';
      this.myid = wx.getStorageSync('userId') || '';
      console.log('aaaaaaaa', this.msgCont)
//            wx.setNavigationBarTitle({
//                title: "姓名"
//            });
    },
    onUnload(){
      wx.setStorageSync('sendId', '');
      this.isShow = false;
    },
    onShow(){
      let v = this;
      this.isShow=true;
      const { type, specId, userId, cardId, logo, wxCode, phone, name  } = this.$root.$mp.query;
      this.appHeight = wx.getSystemInfoSync().windowHeight;
      this.wxCode = wxCode || '';
      this.phone = phone || '';
      this.userlogo = logo || '';
      this.seedName = name || '';
      this.sendId = userId;
      this.myPhone = wx.getStorageSync('phone')  || '';
      wx.setStorageSync('sendId', userId);
      // 获取聊天记录
      let param = {
        code: 105,
        type: type,
        specId,
        clientNum: 0,
        pageSize: 20,
        cardId: cardId,
        targetId: userId,
      }
      this.params = param;
      WebSocket.getChatRecord(param)
      wx.setNavigationBarTitle({
        title: v.$root.$mp.query.name
      });


      console.log("跳转---", this.$root.$mp.query.type, this.$root.$mp.query.cardId, this.$root.$mp.query.logo);

    },
    async onPullDownRefresh() {
      this.params.clientNum = this.msgCont.data.length;
      WebSocket.getChatRecord(this.params);
      setTimeout(()=>{
        wx.stopPullDownRefresh();
      }, 3*1000)
    },
    methods: {
      ...mapActions(['add','change']),
      inputConfirm(){
        console.log('完成 -- ', this.input_word)
      },
      contactMe(){
        WebSocket.sendMessage({
          code: 103,
          message: this.myPhone,
          messageType: 4,
          targetId: this.$root.$mp.query.userId
        })
      },
      getPhoneNumber(e){
        console.log(e);
        WXAJAX.POST({
          phoneData:  e.target.encryptedData,
          phoneIv: e.target.iv,
        }, '', '/home/getWxPhone')
          .then(res=>{
            wx.setStorageSync('phone',res) ;
            this.myPhone = res;
            this.contactMe();
          });
      },
      getTime(){
        let priceObj = {};

        if(this.msgCont.data){
          let times = this.msgCont.data.map((res, idx) => {
            if ( res.messageType == 3 ) priceObj[idx] = res.message.price/100;
            return res.time
          });
          let asd = {};
          asd[0]=this.dateF(times[0]);
          for (let i = 1; i < times.length; i++) {
            let a = (times[i] - times[i - 1]) / 1000 / 60;

            if (a > 3) {
              asd[i] = this.dateF(times[i]);
            }
          }
          this.$set(this, 'indexs', asd);
          this.$set(this, 'priceObj', priceObj);
        }
      },
      dateF(data){
        let year = new Date(data).getFullYear();
        let month = new Date(data).getMonth() + 1;
        let day = new Date(data).getDate();
        let h = (new Date(data).getHours() - 10) < 0 ? "0" + new Date(data).getHours() : new Date(data).getHours();
        let m = (new Date(data).getMinutes() - 10) < 0 ? "0" + new Date(data).getMinutes() : new Date(data).getMinutes();
        let s = (new Date(data).getSeconds() - 10) < 0 ? "0" + new Date(data).getSeconds() : new Date(data).getSeconds();
        let newDate = new Date();
        let year1 = newDate.getFullYear();
        let month1 = newDate.getMonth() + 1;
        let day1 = newDate.getDate();
        let result = '';
        if (year === year1 && month === month1 && day === day1) {
          result = h + ":" + m
        }
        else {
          result = month + "月" + day + ' ' + h + ":" + m;
        }
        return result
      },
//            发送消息
      getcomment(data){
        if (!data.trim()) return;

        let messageSend = {};
        messageSend.message = data;
        messageSend.messageType = 1;
        messageSend.sendId = wx.getStorageSync('userId');
        messageSend.type = 0;
        messageSend.time=(new Date()).getTime();
        messageSend.targetId = this.$root.$mp.query.userId;
        console.log("发送消息----", this.messageCont);
//        this.$forceUpdate();
        let v = this;
        WebSocket.sendMessage({
          code: 103,
          message: data,
          messageType: 1,
          targetId: v.$root.$mp.query.userId
        })
        // this.add(messageSend);
        this.change();
//              console.log("监听连接打开--",res,that.message,that.$root.$mp.query.type);
        // this.connect();
      },
      addWx(){
        if(!this.wxCode.trim()){
          wx.showToast({
            title: '未绑定微信号',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        let v = this;
        wx.setClipboardData({
          data: this.wxCode,
          success: function (res) {
            wx.getClipboardData({
              success: function (res) {
                /* wx.showToast({
                 title: '复制成功'
                 })*/
                v.isShowCourse =  true;
                v.pageFixed = true;
                setTimeout(function () {
                  v.pageFixed = false;
                }, 2000)
              }
            })
          }
        })
      },
      makePhone(){
        if(!this.phone.trim()){
          wx.showToast({
            title: '未绑定手机号',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        wx.makePhoneCall({
          phoneNumber: this.phone,
        })
      },
      page_turn(url, id){
        wx.switchTab({url: '../' + url + '/main'})
      }
    },
    watch:{
      msgCont:{
        handler(){

          this.getTime();
        },
        deep: true,
      },
      changePosition(){
        setTimeout(()=>{
          if (this.isShow) {
            wx.pageScrollTo({ scrollTop: 999999999})
          }
        }, 100)
        // wx.createSelectorQuery().select('#CONT').boundingClientRect(function(rect){
        //   console.log(rect)
        //   // 使页面滚动到底部
        //
        // }).exec()
      }
    },
    computed: {
      ...mapGetters(['msgCont', 'currentCompany','changePosition']),
    }
  }
</script>

<style>
  .bottom-chat{
    position: absolute;
    left: 0;
    right: 0;
    bottom: 50px;
  }
  .sys-message{
    display: inline-block;
    text-align: center;
    height: 25px;
    line-height: 25px;
    font-size: 14px;
    color: #a8a8a8;
    border-radius: 999px;
    background: #e8e8e8;
    padding: 0 20px;
    margin-bottom: 15px;
  }
  .fix.toppage {
    position: fixed;
    top: 0;
    width: 100%;
    overflow: hidden;
  }
  .w250{
    max-width: 250px;
    width: auto;
  }
</style>
